package com.xiong.ai.strategy;

import com.xiong.ai.exception.BusinessException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @program: ai
 * @description:
 * @author: Mr.熊
 * @create: 2024-05-31 11:26
 **/
@Component
public class PdfStrategy implements FileStrategy {

    protected final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Override
    public String doAnalyze(MultipartFile file) {
        String text = null;
        LOGGER.info("pdf文件解析开始");
        try {
            // 加载PDF文档
            PDDocument document = PDDocument.load(file.getInputStream());
            // 创建PDFTextStripper对象来提取文本
            PDFTextStripper pdfStripper = new PDFTextStripper();
            // 从PDF文档中提取文本
            text = pdfStripper.getText(document);
            // 关闭PDF文档
            document.close();
        } catch (IOException e) {
            throw new BusinessException("文件读取失败");
        }
        if (text == null) {
            throw new BusinessException("文件读取失败");
        }
        LOGGER.info("pdf文件解析完成");
        return text;
    }
}
